"""
扫描账号管理模块
"""
from typing import List, Dict, Any
from sqlalchemy.exc import SQLAlchemyError
from .models import ScanAccount
from .sqlalchemy_database import SQLAlchemyDatabaseManager
import logging
from datetime import datetime  # 添加正确的导入
import json

logger = logging.getLogger(__name__)

class ScanAccountManager:
    def __init__(self):
        """初始化扫描账号管理器"""
        self.db = SQLAlchemyDatabaseManager()
    
    def get_active_accounts(self) -> List[Dict[str, Any]]:
        """
        获取所有活跃的扫描账号
        
        Returns:
            List[Dict]: 活跃账号列表
        """
        try:
            session, query = self.db.query_with_session(ScanAccount)
            try:
                accounts = query.filter(ScanAccount.status == 1)\
                    .filter(ScanAccount.alive == 1)\
                    .all()
                
                return [{
                    'id': account.id,
                    'name': account.name,
                    'device_id': account.device_id,
                    'uu_token': account.uu_token,
                    'status': account.status,
                    'alive': account.alive,
                    'locked': account.locked,
                    'min_interval': account.min_interval,
                    'uu_user_id': account.uu_user_id,
                    'nickname': account.nickname,
                    'steam_id': account.steam_id,
                    'alive_times': account.alive_times,
                    'uk': account.uk  # 添加uk字段
                } for account in accounts]
            finally:
                session.close()
                
        except SQLAlchemyError as e:
            print(f"获取活跃账号时发生错误: {str(e)}")
            return []
    
    def get_accounts(self, keyword: str = None, limit: int = None, offset: int = None) -> List[Dict[str, Any]]:
        """
        获取所有账号并格式化为表格显示所需的格式，支持搜索和分页
        
        Args:
            keyword: 搜索关键词
            limit: 每页数量
            offset: 偏移量
            
        Returns:
            List[Dict]: 账号列表
        """
        try:
            session, query = self.db.query_with_session(ScanAccount)
            try:
                # 如果有搜索关键词
                if keyword:
                    query = query.filter(ScanAccount.name.like(f"%{keyword}%"))
                
                # 如果有分页
                if limit is not None and offset is not None:
                    query = query.limit(limit).offset(offset)
                    
                accounts = query.all()
                
                formatted_accounts = []
                for account in accounts:
                    formatted_account = {
                        "id": account.id,
                        "name": account.name,
                        "device_id": account.device_id,
                        "nickname": account.nickname,
                        "status": account.status,
                        "app_status": 1 if account.status == 1 else 0,  
                        "uu_status": 1 if account.alive == 1 else 0,  
                        "alive": account.alive,
                        "alive_times": account.alive_times,
                        "invalid_desc": account.invalid_desc,
                        "update_at": account.update_at,
                        "uu_token": account.uu_token,
                        "uu_user_id": account.uu_user_id,
                        "uk": account.uk,
                        "max_interval": account.min_interval,
                        "create_at": account.create_at
                    }
                    formatted_accounts.append(formatted_account)
                    
                return formatted_accounts
            finally:
                session.close()
                
        except SQLAlchemyError as e:
            print(f"获取账号列表时发生错误: {str(e)}")
            return []
    
    def get_account_by_id(self, account_id):
        """根据ID获取账号信息
        
        Args:
            account_id: 账号ID
            
        Returns:
            dict: 账号信息字典，如果未找到返回None
        """
        try:
            session, query = self.db.query_with_session(ScanAccount)
            try:
                account = query.filter(ScanAccount.id == account_id).first()
                if account:
                    return {
                        "id": account.id,
                        "name": account.name,
                        "uu_token": account.uu_token,  # 添加uu_token字段，与token保持一致
                        "device_id": account.device_id,  # 添加device_id字段
                        "uk": account.uk,  # 添加uk字段
                        "uu_user_id": account.uu_user_id,
                        "tags": account.tags,
                        "usage_frequency": account.min_interval,  
                        "status": account.status,
                        "alive": account.alive,
                        "created_at": account.create_at,  
                        "updated_at": account.update_at  
                    }
                return None
            finally:
                session.close()
        except Exception as e:
            logger.error(f"获取账号信息时发生错误: {str(e)}")
            return None

    def get_accounts_by_ids(self, account_ids: List[int]) -> List[Dict[str, Any]]:
        """根据ID列表批量获取账号信息
        
        Args:
            account_ids: 账号ID列表
            
        Returns:
            List[Dict]: 账号信息列表，每个账号的格式与get_account_by_id相同
        """
        try:
            session, query = self.db.query_with_session(ScanAccount)
            try:
                accounts = query.filter(ScanAccount.id.in_(account_ids)).all()
                return [{
                    "id": account.id,
                    "name": account.name,
                    "token": account.uu_token,
                    "uu_user_id": account.uu_user_id,
                    "tags": account.tags,
                    "usage_frequency": account.min_interval,
                    "status": account.status,
                    "alive": account.alive,
                    "created_at": account.create_at,
                    "updated_at": account.update_at
                } for account in accounts]
            finally:
                session.close()
        except Exception as e:
            logger.error(f"批量获取账号信息时发生错误: {str(e)}")
            return []

    def add_account(self, account_data: Dict[str, Any]) -> bool:
        """
        添加或更新扫描账号
        
        Args:
            account_data: 账号数据，包含以下字段：
                - name: 账号名称
                - uu_token: UU令牌
                - min_interval: 最小扫描间隔（秒）
                - status: 账号状态 (1: 活跃, 0: 禁用)
                - device_id: 设备ID
                - uu_user_id: UU用户ID
                - nickname: 昵称
                - steam_id: Steam ID
                - tags: 标签列表
            
        Returns:
            bool: 是否添加成功
        """
        try:
            session, query = self.db.query_with_session(ScanAccount)
            try:
                # 检查是否已存在相同uu_user_id的账号
                uu_user_id = account_data.get('uu_user_id')
                if not uu_user_id:
                    print("缺少uu_user_id")
                    return False
                    
                existing_account = query.filter(ScanAccount.uu_user_id == uu_user_id).first()
                
                # 处理标签
                tags = json.dumps(account_data.get('tags', []))
                account_data['tags'] = tags
                
                if existing_account:
                    # 更新现有账号
                    for key, value in account_data.items():
                        if hasattr(existing_account, key):
                            setattr(existing_account, key, value)
                    self.db.update_obj(existing_account)
                else:
                    # 创建新账号
                    account_data.update({
                        'alive': 1,  # 默认为存活状态
                        'locked': 0  # 默认为未锁定状态
                    })
                    new_account = ScanAccount(**account_data)
                    self.db.add(new_account)
                
                return True
                
            finally:
                session.close()
                
        except SQLAlchemyError as e:
            print(f"添加或更新账号时发生错误: {str(e)}")
            return False
    
    def update_account_status(self, account_id: int, status: int = 1, 
                            alive: bool = True, locked: bool = False) -> bool:
        """
        更新账号状态
        
        Args:
            account_id: 账号ID
            status: 账号状态 (1: 活跃, 0: 禁用)
            alive: 是否存活
            locked: 是否锁定
            
        Returns:
            bool: 是否更新成功
        """
        try:
            account = self.db.get_by_id(ScanAccount, account_id)
            if account:
                account.status = status
                account.alive = alive
                account.locked = locked
                self.db.update_obj(account)
                return True
            return False
        except SQLAlchemyError as e:
            print(f"更新账号状态时发生错误: {str(e)}")
            return False
    
    def update_account_uk(self, account_id: int, uk: str, device_id: str = None) -> bool:
        """更新账号的uk值
        
        Args:
            account_id: 账号ID
            uk: 新的uk值
            device_id: 新的设备ID，可选（已废弃，不再使用）
            
        Returns:
            bool: 是否更新成功
        """
        try:
            account = self.db.get_by_id(ScanAccount, account_id)
            if account:
                account.uk = uk
                account.update_at = int(datetime.now().timestamp() * 1000)
                self.db.update_obj(account)
                return True
            print(f"找不到ID为 {account_id} 的账号")
            return False
        except SQLAlchemyError as e:
            print(f"更新账号uk时发生错误: {str(e)}")
            return False
    
    def update_uu_alive(self, account_id: int, alive: int, desc: str = "") -> bool:
        """更新悠悠账号存活状态
        
        Args:
            account_id: 账号ID
            alive: 存活状态
            desc: 失效描述
            
        Returns:
            bool: 是否成功
        """
        try:
            session, query = self.db.query_with_session(ScanAccount)
            try:
                account = query.filter(ScanAccount.id == account_id).first()
                if not account:
                    return False
                
                account.alive = alive
                account.invalid_desc = desc if not alive else ""
                account.update_at = int(datetime.now().timestamp() * 1000)
                
                if alive:
                    account.alive_times += 1
                    
                session.commit()
                return True
            finally:
                session.close()
        except Exception as e:
            logger.error(f"更新账号存活状态时发生错误: {str(e)}")
            return False
    
    def delete_account(self, account_id: int) -> bool:
        """
        删除扫描账号
        
        Args:
            account_id: 账号ID
            
        Returns:
            bool: 是否删除成功
        """
        try:
            account = self.db.get_by_id(ScanAccount, account_id)
            if account:
                self.db.delete_obj(account)
                return True
            return False
        except SQLAlchemyError as e:
            print(f"删除账号时发生错误: {str(e)}")
            return False

def main():
    """测试账号管理功能"""
    manager = ScanAccountManager()
    
    # 添加测试账号
    manager.add_account({"name": "test_account", "uu_token": "test_token", "min_interval": 30, "status": 1, "device_id": "test_device", "uu_user_id": "test_user", "nickname": "test_nickname", "steam_id": "test_steam", "tags": ["tag1", "tag2"]})
    
    # 获取所有活跃账号
    accounts = manager.get_active_accounts()
    print("\n活跃账号列表:")
    for account in accounts:
        print(f"账号ID: {account['id']}")
        print(f"设备ID: {account['device_id']}")
        print(f"UU令牌: {account['uu_token']}")
        print(f"状态: {account['status']}")
        print(f"存活: {account['alive']}")
        print(f"锁定: {account['locked']}")
        print(f"最小间隔: {account['min_interval']}")
        print()

if __name__ == "__main__":
    main()
